import React, { PureComponent } from 'react'
import { message, Popconfirm, Timeline, Badge, Table, Card } from 'antd'
import { connect } from 'dva'
import moment from 'moment'
import PropTypes from 'prop-types'
import PageHeaderLayout from '@/layouts/PageHeaderLayout'
import TemplateCard from '@/support/components/TemplateCard'
import PateoStandardTable from '@/common/PateoTable/PateoStandardTable'
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import * as G from '@/utils/common'
import PateoAuthButtons from '@/common/PateoAuthButtons/PateoAuthButtons';
import {Prompt} from 'react-router-dom';
import { routerRedux } from 'react-router-dom';
import { indexOf, isInteger } from 'lodash'
import Ellipsis from "@/components/Ellipsis";
import { Form } from '@ant-design/compatible';
import styles from './index.less';
import classNames from 'classnames';
import { getDicByKey, getDictOptionsByCode } from '@/support/common';

@connect((state) => ({
  letterCheck: state.letterCheck,
  mailManage: state.mailManage,
  menu: state.menu,
}))
@Form.create()
export default class mailManage extends PureComponent {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.any,
  };
  state = {
    formValues: {},
    creditTypeOptions: [],
  }

  componentDidMount() {
    this.getDic();
    this.getTableData()
  }
  getTableData = () => {
    const { dispatch } = this.props
    const { formValues } = this.state
    dispatch({
      type: "mailManage/getList",
      payload: {
        url: '/mscreditbusiness/station/information/page',
        ...formValues 
      },
    })
  }
  getDic = () =>{
    const {menu: { dicData }} = this.props;
    const typeOption = getDictOptionsByCode(dicData, 'creditType');
    this.setState({
      creditTypeOptions: typeOption.map(e => ({
            label: e.label,
            value: e.value,
          })),
   })
  }
  handleTableChange = (page) => {
    const { dispatch } = this.props
    const { formValues } = this.state
    const params = {
      curPage: page.current,
      pageSize: page.pageSize,
      ...formValues,
    }
    dispatch({
      type: "mailManage/getList",
      payload: {
        url: '/mscreditbusiness/station/information/page',
        ...params 
      },
    })
  }

  handleRangePicker = val => {
    if (val.createDateRange && val.createDateRange.length !== 0) {
      val['startTime'] = moment(val.createDateRange[0]).format('YYYY-MM-DD HH:mm:ss');
      val['endTime'] = moment(val.createDateRange[1]).format('YYYY-MM-DD HH:mm:ss');
    }
    delete (val["createDateRange"]);
  }
  viewDetails = (record) =>{ //详情
    // 将站内信sid换成recordId存入，查询该条风控预警详情
    record.uuid = record.recordUuid;
    console.log('record', record);
    sessionStorage.setItem('warningRecord', JSON.stringify(record))
    sessionStorage.setItem("typeOption", JSON.stringify(this.state.creditTypeOptions));
    sessionStorage.setItem(
      "warningRecordBackPath",
      "/creditPlatform/mailManage"
    );
    this.props.dispatch(
      routerRedux.push({
        pathname:
          "/creditPlatform/warningRecordDetail"
      })
    )
  }
  handled = (key) =>{ // 处理
    console.log('id', key);
    const { dispatch } = this.props
    const list=[];
    list.push(key);
    // const param = JSON.stringify(informationIds);
    console.log('param', list);
    const param = {
      informationUuids: list,
      operateType: 1,
    };
    dispatch({
      type: 'mailManage/postObjWithRes',
      payload: { url: '/mscreditbusiness/station/information/deal', ...param},
      callback: (response) =>{
       if(response.statusCode === "0"){
        message.success('处理成功！');
        this.getTableData()
       }else{
        message.error(response.statusMessage);
       }
  }
})
    
}
  
  leavePage(location){ // 页面跳转  只要退出当前站内信页面，所有未读消息均设置为已读消息
    console.log('location', location.pathname);
    const { dispatch } = this.props
    const { formValues } = this.state
    // 将目前收到的未读信息均设置为已读
    const data = sessionStorage.getItem("unreadIds") || "";
    console.log('type', typeof(data));
    console.log('data', data)
    if(data){//存在未读信息
    const list = (data.split(','));
    console.log('list',list);
    const params = {
      informationUuids: list,
      operateType: 2
    };
    console
    dispatch({
      type: 'mailManage/postObjWithRes',
      payload: { url: '/mscreditbusiness/station/information/deal', ...params},
      callback: (response) =>{
       if(response.statusCode === "0"){
       //获取未读消息数量更新铃铛上数量
       dispatch({
        type: 'letterCheck/getunRead',
        callback: (res) =>{
          sessionStorage.setItem('unreadIds', res.data);
        }
      }) 
       }else{
        // message.error(response.statusMessage);
       }
     }
    })
    }else{
      //获取未读消息数量更新铃铛上数量
      dispatch({
        type: 'letterCheck/getunRead',
        callback: (res) =>{
          sessionStorage.setItem('unreadIds', res.data);
        }
      }) 
    }
  }
  /**
   * 参数校验
   * @param fieldsValue
   */
  dataFormat = (fields) => {
    if (G.isNotEmptyAndNil(fields['createDateRange'])) {
      const [start, end] = fields.createDateRange;
      fields['startTime'] = moment(start).format('YYYY-MM-DD HH:mm:ss');
      fields['endTime'] = moment(end).format('YYYY-MM-DD HH:mm:ss');
      delete fields['createDateRange'];
    }
    return fields;
  };
  render() {
    const {dispatch, permissions, location: { pathname = '/' },} = this.props
    const {mailManage:{rows = [], pagination}} = this.props;
    const { formValues, creditTypeOptions } = this.state
    const searchItems = [
      {
        type: 'input',
        title: 'VIN号',
        key: 'vin',
      },
      {
        title: '授信类型',
        type: 'select',
        selectOptions: creditTypeOptions,
        key: 'creditType',
      },
      {
        title: '处理状态',
        type: 'select',
        selectOptions: [
          { label: '未处理', value: 0 },
          { label: '已处理', value: 1 }
        ],
        key: 'dealStatus',
      },
      {
        title: '收到时间',
        type: 'rangePicker',
        key: 'createDateRange',
      },
    ]
    const columns = [
      {
        title: '',
        dataIndex: 'readStatus',
        render: (text, record) => {
          if (text === 0) {//未处理  
            return <Badge status="error"/>;
          }else{
          return '';
          }
        },
      },
      {
        title: '预警时间',
        dataIndex: 'riskTriggerDate',
        ellipsis: true,
      }, {
        title: '预警内容',
        dataIndex: 'riskWarnMsg',
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      }, {
        title: '触发的异常事件',
        dataIndex: 'riskEventContent',
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      }, {
        title: 'VIN号',
        dataIndex: 'vin',
        ellipsis: true,
      },{
        title: '授信类型',
        dataIndex: 'creditType',
         render: (text) => {
          if (text == null) {
            return '';
          }
          return getDicByKey(this.context.dicData, `creditType`, text.toString());
          }
        },{
        title: '车辆风控状态',
        dataIndex: 'riskStatus',
         render: (text) => {
          if(text === 'normal'){
            return '正常'
          }else if(text === 'limp'){
            return '跛行'
          }else if(text === 'lock'){
            return '锁车'
          }else{
            return ''
          }
          }
        },
      {
        title: '预警状态',
        dataIndex: 'riskWarnStatus',
        render: (text) => {
          if(text === 0){
            return '非预警'
          }else if(text === 1){
            return '已预警'
          }else{
            return ''
          }
        }
      },{
        title: '处理状态',
        dataIndex: 'dealStatus',
        render: (text) => {
          if(text === 0){
            return '未处理'
          }else if(text === 1){
            return '已处理'
          }else{
            return ''
          }
        }
      }, {
        title: '车机告警状态',
        dataIndex: 'warnStatus',
        render: (text) => {
          if(text == 0){
            return '正常'
          }else if(text == 1){
            return '车机告警'
          }else {
            return ''
          }
        }
      }, {
        title: '操作',
        dataIndex: '操作',
        fixed: 'right',
        align: "center",
        // width: 180,
        render: (text, record) => {
          const btns = [
            {
              title: '详情',
              key: 'detail',
              onConfirm: () => this.viewDetails.bind(this)(record), //跳转到该条风控预警详情页 
            },
            {
              title: '标识为已处理',
              key: 'action',
              onConfirm: () => this.handled.bind(this)(record.uuid),
            },
          ]
         
          if (record.dealStatus === 0) {
          return <PateoAuthButtons authStr="mailManage_show" btns={btns} />;
          } else{
            return ''
          }
       }
    }
  ]
  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    ...pagination,
    showTotal: () => <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>,
  } 
    return (
        <div className={classNames(styles['mailSearchDiv'])}>
          <Card bordered={false}>
          <PateoSearchForm
            onRef={(val) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'mailManage/getList',
              url: '/mscreditbusiness/station/information/page',
            }}
            saveFormValues={(val) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFormReset={() => this.setState({ formValues: {} })}
            handleFieldsValue={this.dataFormat}
          />
          </Card>
          <Card bordered={false} style={{ marginTop: 10 }}>
          <Table
              rowKey={record => record.uuid}
              columns={columns}
              dataSource={rows?  rows: []}
              // loading={loading}
              formValues={this.state.formValues}
              pagination={paginationProps}
              onChange={this.handleTableChange}
              scroll={{ x: "max-content" }}
            />
          </Card>
           <div>
          <Prompt
            when={true}
            message={this.leavePage.bind(this)}
          />
        </div>
        </div>
    )
  }
}
